<?php
/**
 * Created by PhpStorm.
 * User: meiyun1
 * Date: 2017/3/16
 * Time: 下午2:51
 */

namespace App\Http\Controllers\App;

use App\App\Services\SMSClientService;
use App\App\Services\WechatService;
use App\Exceptions\ExceptionCode;
use Illuminate\Http\Request;

class OauthController extends \App\Http\Controllers\Controller
{
    private $request;
    private $wechatService;
    private $smsClientService;
    public function __construct(Request $request, WechatService $wechatService, SMSClientService $SMSClientService)
    {
        $this->request = $request;
        $this->wechatService = $wechatService;
        $this->smsClientService = $SMSClientService;
    }

    public function oauth()
    {
        $oauth = $this->wechatService->getWechatApp()->oauth;
        $user = $oauth->user()->toArray();
        $target_url = session('target_url');
        return response()->redirectTo($target_url)->cookie('openid', $user['id']);
    }

    public function sendSmsCode()
    {
        $mobile = $this->request->request->get('mobile');
        if (empty($mobile)) {
            return $this->respondJson([
                'code'=>ExceptionCode::GENERAL,
                'message'=>'手机号不能为空'
            ]);
        }
        if (!preg_match("/^(0|86|17951)?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$/", $mobile)) {
            return $this->respondJson([
                'code'=>ExceptionCode::GENERAL,
                'message'=>'手机号格式错误'
            ]);
        }
        //return $this->respondJson(['message'=>'发送成功']);
        return $this->respondJson($this->smsClientService->sendMsg($mobile));
    }

    public function checkMobileCode()
    {
        $mobile = $this->request->request->get('mobile');
        $code = $this->request->request->get('code');
        if (empty($mobile)) {
            return $this->respondJson([
                'code'=>ExceptionCode::GENERAL,
                'message'=>'手机号不能为空'
            ]);
        }
        if (empty($code)) {
            return $this->respondJson([
                'code'=>ExceptionCode::GENERAL,
                'message'=>'验证码不能为空'
            ]);
        }
        $result = $this->smsClientService->checkMobileCode($mobile, $code);
        if ($result['code'] == 0) {
            $session = $this->request->session();
            $session->put('mobile', $mobile);
        }
        return $this->respondJson($result);
    }
}
